import 'dart:convert';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:formz/formz.dart';
import 'package:get/get.dart';
import 'package:hj_crm/const/constant.dart';
import 'package:hj_crm/entity/captcha_entity.dart';
import 'package:hj_crm/form/home_page.dart';
import 'package:hj_crm/utils/connection_status.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/network_cubit.dart';
import 'package:hj_crm/utils/sp_utils.dart';
import 'package:hj_crm/utils/toast_utils.dart';

class LoginPageWidget extends StatefulWidget {
  const LoginPageWidget({super.key});

  @override
  State<LoginPageWidget> createState() => _LoginPageWidgetState();
}

class _LoginPageWidgetState extends State<LoginPageWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('宏基客户管理系统')),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: SingleChildScrollView(child: const LoginPage()),
        ),
      ),
    );
  }
}

/// 登录页
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _key = GlobalKey<FormState>();
  late LoginState _state;
  late final TextEditingController _emailController;
  late final TextEditingController _passwordController;
  late final TextEditingController _captchaController;

  final RequestRepository repository = Get.find<RequestRepository>();

  bool requestSuccess = false;

  /// 图形验证码
  Uint8List? imageData;
  String? captchaId;

  void _onEmailChanged() {
    setState(() {
      _state = _state.copyWith(email: Email.dirty(_emailController.text));
    });
  }

  void _onPasswordChanged() {
    setState(() {
      _state = _state.copyWith(
        password: Password.dirty(_passwordController.text),
      );
    });
  }

  void _onCodeChanged() {
    setState(() {
      _state = _state.copyWith(code: Code.dirty(_captchaController.text));
    });
  }

  Future<void> _onSubmit() async {
    FocusScope.of(context).unfocus();
    if (!_key.currentState!.validate()) return;

    setState(() {
      _state = _state.copyWith(status: FormzSubmissionStatus.inProgress);
    });

    try {
      await _submitForm();
      _state = _state.copyWith(status: FormzSubmissionStatus.success);
    } catch (_) {
      _state = _state.copyWith(status: FormzSubmissionStatus.failure);
    }

    if (!mounted) return;

    setState(() {});

    FocusScope.of(context)
      ..nextFocus()
      ..unfocus();

    // const successSnackBar = SnackBar(
    //   content: Text('提交成功 🎉'),
    // );
    // const failureSnackBar = SnackBar(
    //   content: Text('发生一些错误 🚨'),
    // );

    // ScaffoldMessenger.of(context)
    //   ..hideCurrentSnackBar()
    //   ..showSnackBar(
    //     _state.status.isSuccess ? successSnackBar : failureSnackBar,
    //   );

    // if (_state.status.isSuccess) {
    //   Navigator.of(context).push(
    //     MaterialPageRoute(
    //       builder: (context) => UserListWidget(), // 跳转到的新页面
    //     ),
    //   );
    //   _resetForm();
    // }
  }

  Future<void> _submitForm() async {
    await login().then((value) => print('登录成功'));
    // if (widget.seed.nextInt(2) == 0) throw Exception();
  }

  void _resetForm() {
    _key.currentState!.reset();
    _emailController.clear();
    _passwordController.clear();
    _captchaController.clear();
    setState(() => _state = LoginState());
  }

  @override
  void initState() {
    super.initState();
    _state = LoginState();
    _emailController = TextEditingController(text: _state.email.value)
      ..addListener(_onEmailChanged);
    _passwordController = TextEditingController(text: _state.password.value)
      ..addListener(_onPasswordChanged);
    _captchaController = TextEditingController(text: _state.code.value)
      ..addListener(_onCodeChanged);
    getCaptcha();

    NetworkCubit.networkListener<NetworkConnectionStatus>((event) {
      switch (event) {
        case NetworkConnectionStatus.connected:
          if (!requestSuccess) getCaptcha();
          NetworkCubit.distroy();
          break;
        case NetworkConnectionStatus.disconnected:
          ToastUtils.show('网络连接失败，请检查网络连接');
          break;
        case NetworkConnectionStatus.slow:
          ToastUtils.show('网络较慢');
          break;
      }
    });
  }

  getCaptcha() {
    repository.getCaptcha(
      success: (data) {
        requestSuccess = true;
        final captcha = CaptchaEntity.fromJson(data);
        if (captcha.captcha != null && captcha.captcha!.isNotEmpty) {
          // 移除前缀
          final String base64WithoutPrefix = captcha.captcha!.split(',').last;

          // 解码 Base64 字符串为 Uint8List
          imageData = base64Decode(base64WithoutPrefix);
          captchaId = captcha.captchaId;
          setState(() {});
        }
      },
      fail: (code, msg) {
        ToastUtils.show('获取验证码失败: code: $code, msg: $msg');
        print('code: $code, msg: $msg');
      },
    );
  }

  /// 登录
  login() {
    repository.login(
      username: _emailController.text,
      password: _passwordController.text,
      captchaId: captchaId,
      verifyCode: _captchaController.text,
      success: (data) {
        //ture是经销商， 只能处理用户，   false  两个权限都有
        Constant.isDealer = data.isDealer ?? true;
        Constant.dualSystem = !Constant.isDealer;

        SpUtil.updateDualSystem(Constant.dualSystem);

        /// 删除用户信息并更新token，token用以判断是否需要登录
        /// token 有效期,未知?
        SpUtil.deleteUserInfo();

        SpUtil.updateToken(data.accessToken!);
        Get.off(const HomePageWidget());
        _resetForm();
      },
      fail: (code, msg) {
        ToastUtils.show('登录失败: code: $code, msg: $msg');
      },
    );
  }

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    _captchaController.dispose();
    NetworkCubit.distroy();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _key,
      child: Column(
        children: [
          TextFormField(
            key: const Key('myForm_emailInput'),
            controller: _emailController,
            decoration: const InputDecoration(
              icon: Icon(Icons.account_circle),
              labelText: '手机号',
              helperText: '请输入手机号',
            ),
            validator: (value) => _state.email.validator(value ?? '')?.text(),
            keyboardType: TextInputType.phone,
            textInputAction: TextInputAction.next,
          ),
          TextFormField(
            key: const Key('myForm_passwordInput'),
            controller: _passwordController,
            decoration: const InputDecoration(
              icon: Icon(Icons.lock),
              helperText: '请至少输入6位密码',
              helperMaxLines: 1,
              labelText: '密码',
              errorMaxLines: 2,
            ),
            validator: (value) => _state.password.validator(value ?? '')?.text(),
            obscureText: true,
            textInputAction: TextInputAction.done,
          ),

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              TextFormField(
                key: const Key('myForm_captchaInput'),
                decoration: const InputDecoration(
                  icon: Icon(Icons.image),
                  helperText: '请输入图形验证码',
                  helperMaxLines: 1,
                  labelText: '验证码',
                  errorMaxLines: 2,
                  constraints: BoxConstraints(maxWidth: 200),
                ),
                keyboardType: TextInputType.visiblePassword,
                controller: _captchaController,
                validator: (value) => _state.code.validator(value ?? '')?.text(),
                textInputAction: TextInputAction.done,
              ),
              if (imageData != null)
                GestureDetector(
                  onTap: getCaptcha,
                  child: Container(
                      alignment: Alignment.centerLeft,
                      child: Column(
                        children: [
                          Image.memory(
                            imageData!,
                            width: 110,
                            height: 36,
                          ),
                          const SizedBox(height: 2),
                          const Text('(点击图形刷新)',
                              style: TextStyle(
                                color: Colors.black45,
                              )),
                        ],
                      )),
                ),
            ],
          ),

          const SizedBox(height: 24),
          if (_state.status.isInProgress)
            const CircularProgressIndicator()
          else
            ElevatedButton(
              style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(Colors.blue),
              ),
              key: const Key('myForm_submit'),
              onPressed: _onSubmit,
              child: Container(
                alignment: Alignment.center,
                width: 200,
                child: const Text(
                  '登录',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          const SizedBox(height: 60)
          // Constant.isDealer
          //     ? const SizedBox()
          //     : Constant.isDistributorSystem
          //         ? TextButton(
          //             key: const Key('myForm_distributor_submit'),
          //             onPressed: () {
          //               Constant.isDistributorSystem = false;
          //               SpUtil.updateDistributorSystem(false);
          //               widget.systemChanged.call(false);
          //               setState(() {});
          //             },
          //             child: const Text('切换到客户管理系统>>',
          //                 style: TextStyle(decoration: TextDecoration.underline)),
          //           )
          //         : TextButton(
          //             key: const Key('myForm_user_submit'),
          //             onPressed: () {
          //               Constant.isDistributorSystem = true;
          //               SpUtil.updateDistributorSystem(true);
          //               widget.systemChanged.call(true);
          //               setState(() {});
          //             },
          //             child: const Text(
          //               '切换到经销商管理系统>>',
          //               style: TextStyle(decoration: TextDecoration.underline),
          //             ),
          //           ),
        ],
      ),
    );
  }
}

class LoginState with FormzMixin {
  LoginState({
    Email? email,
    Code? code,
    this.password = const Password.pure(),
    this.status = FormzSubmissionStatus.initial,
  })  : email = email ?? Email.pure(),
        code = code ?? Code.pure();

  final Email email;
  final Code code;
  final Password password;
  final FormzSubmissionStatus status;

  LoginState copyWith({
    Email? email,
    Code? code,
    Password? password,
    FormzSubmissionStatus? status,
  }) {
    return LoginState(
      email: email ?? this.email,
      code: code ?? this.code,
      password: password ?? this.password,
      status: status ?? this.status,
    );
  }

  @override
  List<FormzInput<dynamic, dynamic>> get inputs => [email, password, code];
}

enum EmailValidationError { invalid, empty }

class Email extends FormzInput<String, EmailValidationError> with FormzInputErrorCacheMixin {
  Email.pure([super.value = '']) : super.pure();

  Email.dirty([super.value = '']) : super.dirty();

  // static final _emailRegExp = RegExp(
  //   r'^[a-zA-Z\d.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z\d-]+(?:\.[a-zA-Z\d-]+)*$',
  // );
  static final _emailRegExp = RegExp(r'^1[3-9]\d{9}$');

  @override
  EmailValidationError? validator(String value) {
    if (value.isEmpty) {
      return EmailValidationError.empty;
    } else if (!_emailRegExp.hasMatch(value)) {
      return EmailValidationError.invalid;
    }

    return null;
  }
}

enum CodeValidationError { invalid, empty }

class Code extends FormzInput<String, CodeValidationError> with FormzInputErrorCacheMixin {
  Code.pure([super.value = '']) : super.pure();

  Code.dirty([super.value = '']) : super.dirty();

  ///四位数字和字母的组合
  static final _codeRegExp = RegExp(r'^[a-zA-Z0-9]{4}$');

  @override
  CodeValidationError? validator(String value) {
    if (value.isEmpty) {
      return CodeValidationError.empty;
    } else if (!_codeRegExp.hasMatch(value)) {
      return CodeValidationError.invalid;
    }
    return null;
  }
}

enum PasswordValidationError { invalid, empty }

class Password extends FormzInput<String, PasswordValidationError> {
  const Password.pure([super.value = '']) : super.pure();

  const Password.dirty([super.value = '']) : super.dirty();

  // static final _passwordRegex = RegExp(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$');
  static final _passwordRegex = RegExp(r'^.{6,}$');

  @override
  PasswordValidationError? validator(String value) {
    if (value.isEmpty) {
      return PasswordValidationError.empty;
    } else if (!_passwordRegex.hasMatch(value)) {
      return PasswordValidationError.invalid;
    }

    return null;
  }
}

extension on EmailValidationError {
  String text() {
    switch (this) {
      case EmailValidationError.invalid:
        return '请输入有效的手机号码，长度为11位';
      case EmailValidationError.empty:
        return '请输入您的手机号';
    }
  }
}

extension on CodeValidationError {
  // ignore: unused_element
  String text() {
    switch (this) {
      case CodeValidationError.invalid:
        return '请输入4位图像验证码';
      case CodeValidationError.empty:
        return '请输入图像验证码';
    }
  }
}

extension on PasswordValidationError {
  String text() {
    switch (this) {
      case PasswordValidationError.invalid:
        return '密码必须至少6位，可以为纯数字';
      case PasswordValidationError.empty:
        return '请输入密码';
    }
  }
}
